<template>
  <div class="article-list">
    <van-pull-refresh
      v-model="isRefreshLoading"
      @refresh="onRefresh"
      :success-text="refreshText"
      style="min-height: 100vh"
    >
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
        :error.sync="error"
        error-text="请求失败，点击重新加载"
      >
        <ArticleItem
          v-for="(article, index) in articleList"
          :key="index"
          :article="article"
        ></ArticleItem>
        <!-- <van-cell
          v-for="(article, index) in articleList"
          :key="index"
          :title="article.title"
        /> -->
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import ArticleItem from '@/components/ArticleItem.vue'
import { getArticles } from '@/api/index.js'
export default {
  name: 'ArticleList',
  components: { ArticleItem },
  data () {
    return {
      articleList: [],
      loading: false,
      finished: false,
      timeStamp: null,
      error: false,
      isRefreshLoading: false,
      refreshText: '刷新成功'
    }
  },
  mounted () {
    // console.log(this.item.name)
  },
  props: {
    item: {
      type: Object,
      required: true
    }
  },
  methods: {
    async onLoad () {
      try {
        // 配置接口所需的请求参数
        const params = {
          channel_id: this.item.id,
          timestamp: this.timeStamp || Date.now(),
          with_top: 1
        }
        // 模拟随机失败情况
        // if (Math.random() > 0.5) {
        //   throw Error
        // }
        const { data: res } = await getArticles(params)
        if (res.data.results.length !== 0) {
          this.articleList.push(...res.data.results)
          this.timeStamp = res.data.pre_timestamp
          this.loading = false
        } else {
          this.finished = true
        }
      } catch (error) {
        this.error = true
        this.loading = false
      }
    },
    // 获取刷新最新数据
    async onRefresh () {
      try {
        // 配置接口所需的请求参数
        const params = {
          channel_id: this.item.id,
          timestamp: Date.now(),
          with_top: 1
        }
        // 模拟随机失败情况
        // if (Math.random() > 0.5) {
        //   throw Error
        // }
        const { data: res } = await getArticles(params)
        this.articleList.unshift(...res.data.results)
        this.refreshText = `成功刷新了${res.data.results.length}条数据`
        this.isRefreshLoading = false
      } catch (error) {
        this.isRefreshLoading = false
        this.refreshText = '刷新失败，请稍后再试'
      }
    }
  }
}
</script>

<style lang="less" scoped>
.article-list {
  overflow-y: auto;
  height: 79vh;
}
</style>
